package com.mos.iot.mqtt.listener.converter;

import java.util.Objects;

public interface MessageConverter {

    <T> T convert(Object value, Class<T> target, T defaultValue) throws IllegalArgumentException;

    default <T> T convertWithCheck(Object value, Class<T> target, T defaultValue, boolean quietly) {
        try {
            if(Objects.nonNull(value) && Objects.nonNull(target) && target.isAssignableFrom(value.getClass())) {
                return (T) value;
            }
            return convert(value, target, defaultValue);
        } catch (Exception e) {
            if(quietly){
                return defaultValue;
            }
            throw e;
        }
    }
}
